<template>
  <div class="admin-customer-service">
    <div class="conversation-list">
      <div
        v-for="conversation in conversations"
        :key="conversation.id"
        class="conversation-item"
        @click="selectConversation(conversation)"
      >
        <span>{{ conversation.userId }}</span>0=
        <span>{{ conversation.lastMessageContent }}</span>
      </div>
    </div>
    <div class="chat-box">
      <div v-for="message in selectedMessages" :key="message.id" class="message">
        <div :class="['message-content', { 'is-me': message.senderId === adminId }]">
          <span>{{ message.content }}</span>
        </div>
      </div>
    </div>
    <div class="input-box">
      <input v-model="inputMessage" placeholder="请输入消息" @keyup.enter="sendMessage" />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script>
import WebSocketService from "../utils/WebSocket/Websocket.js";

export default {
  data() {
    return {
      adminId: "admin", // 假设的管理员ID
      conversations: [], // 会话列表
      selectedConversation: null, // 当前选中的会话
      selectedMessages: [], // 当前会话的消息列表
      inputMessage: "",
      webSocket: null,
    };
  },

  mounted() {
    this.initWebSocket();
    this.loadConversations();
  },
  methods: {
    initWebSocket() {
      this.webSocket = new WebSocketService("ws://localhost:8080/websocket/", this.adminId);
      this.webSocket.handleMessage = this.handleMessage;
    },
    loadConversations() {
      // 模拟从后端加载会话列表
      this.conversations = [
        { id: 1, userId: "admin", lastMessageContent: "你好" },
        // 其他会话...
      ];
    },
    selectConversation(conversation) {
      this.selectedConversation = conversation;
      this.selectedMessages = []; // 清空当前消息列表
      // 模拟从后端加载当前会话的消息
      this.loadMessages(conversation.id);
    },
    loadMessages(conversationId) {
      // 从后端加载消息逻辑
    },
    sendMessage() {
      if (this.inputMessage.trim() === "") return;
      if (!this.selectedConversation) {
        alert("请选择一个会话");
        return;
      }
      const message = {
        conversationId: this.selectedConversation.id,
        senderId: this.adminId,
        receiverId: this.selectedConversation.userId,
        content: this.inputMessage,
      };
      this.webSocket.sendMessage(message);
      this.inputMessage = "";
    },
    handleMessage(data) {
      if (data.type === "chat") {
        // 更新消息列表
        this.selectedMessages.push(data);
      }
    },
  },
  beforeDestroy() {
    if (this.webSocket) {
      this.webSocket.close();
    }
  },
};
</script>

<style scoped>
/* 样式保持不变 */
</style>
